package com.hoperun.product.activity;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hoperun.product.adapter.InputListAdapter;
import com.hoperun.product.adapter.InputListAdapter.onCheckClickListener;
import com.hoperun.product.base.MIP_BaseActivity;
import com.hoperun.product.common.TableNo;
import com.hoperun.product.entity.ProductInputEntity;
import com.hoperun.product.entity.SpinnerEntity;
import com.hoperun.product.net.IServiceImpl;
import com.hoperun.product.net.RequestServiceImpl;
import com.hoperun.product.util.ParseUtils;
import com.hoperun.product.util.SharedPreUtil;
import com.hoperun.product.util.scan.ScanGun;
import com.hoperun.product.view.SimpleDialog;
import com.hoperun.yieldmgryue.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class InputActivity extends MIP_BaseActivity implements OnClickListener {
	/** activity销毁时，存储product的key值 **/
	private final static String PRODUCTLIST = "productList";
	/** activity销毁时，存储三联单号的key值 **/
	private final static String CLOTHTKTNO = "clothTktNo";

	/** listview适配器 **/
	private InputListAdapter mAdapter;
	/** 当前产量列表 **/
	private List<ProductInputEntity> mProductList = new ArrayList<ProductInputEntity>();
	private List<ProductInputEntity> mSaveProductList = new ArrayList<ProductInputEntity>();
	private List<ProductInputEntity> mDeleteProductList = new ArrayList<ProductInputEntity>();

	private ListView mListView;

	private LinearLayout mDateLl;

	private TextView mDateTv;
	private ImageView mClearImg;

	private Button mSearchBtn;

	private Button mDeleteBtn;

	private Button mSaveBtn;
	/** 三联单号，扫描条码自动带出 **/
	private EditText mClothTktNoEt;
	/** 车号 **/
	private EditText mMachineNoEt;

	private TextView mCountTv,mCountTv2;

	/** 记录三联单号 **/
	private String mClothThtNo;
	/** 存储下拉框文本 **/
	private List<String> mSpList = new ArrayList<String>();
	/** 扫描枪控制类 **/
	private ScanGun mScanGun;
	/** 存储日期 **/
	private String mJobDate = "";

	/** 员工工号 **/
	private String mJobNum = "";
	/** 员工登录的车间，text值 **/
	private String mBmmc = "";

//	private SimpleDateFormat dateFormat_ZH = new SimpleDateFormat("yyyy年MM月dd日");
	
	private SimpleDateFormat dateFormat_EN = new SimpleDateFormat("yyyy-MM-dd");

	private boolean isEditClicked = false;
	private int mCount = 0;

	//是否允许调用网络接口
	private boolean isAllow=true;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.input_activity);
		initDate();
		initView();
		initEvent();
		if (savedInstanceState != null) {
			mProductList.clear();
			// toast("大小" + mProductList.size());
			mProductList.addAll((List<ProductInputEntity>) savedInstanceState.getSerializable(PRODUCTLIST));
			// toast("大小" + mProductList.size());
			mAdapter.notifyDataSetChanged();
			checkListview();
			mClothThtNo = savedInstanceState.getString(CLOTHTKTNO);
			mClothTktNoEt.setText(mClothThtNo);

		}
		startGetInputList();
		getSystime();
	}

	private void initDate() {

		mJobDate = dateFormat_EN.format(getDefaultDate().getTime());
		mSpList.add("请选择原因\nVui lòng chọn nguyên  nhân");
		mJobNum = (String) SharedPreUtil.getValue(this, SharedPreUtil.YHM, "");
		mBmmc = (String) SharedPreUtil.getValue(this, SharedPreUtil.BMMC, "");
	}

	private void initView() {
		mListView = (ListView) findViewById(R.id.input_listView);
		mDateLl = (LinearLayout) findViewById(R.id.input_dateLl);
		mDateTv = (TextView) findViewById(R.id.input_dateTv);
		mClothTktNoEt = (EditText) findViewById(R.id.input_clothTktNoEt);
		mMachineNoEt = (EditText) findViewById(R.id.input_machineNoEt);
		mClearImg = (ImageView) findViewById(R.id.input_clearImg);
		mSearchBtn = (Button) findViewById(R.id.input_searchBtn);

		mDeleteBtn = (Button) findViewById(R.id.input_deleteBtn);

		mSaveBtn = (Button) findViewById(R.id.input_saveBtn);
		mCountTv = (TextView) findViewById(R.id.input_countTv);
		mCountTv2 = (TextView) findViewById(R.id.input_countTv2);
		mAdapter = new InputListAdapter(this, mProductList, mJobDate);
		// 这一步很关键，不要忘了，使得adapter支持局部刷新
		mAdapter.setListView(mListView);
		//mDateTv.setText(dateFormat_ZH.format(Calendar.getInstance().getTime()));
		//mDateTv.setText(dateFormat_ZH.format(getDefaultDate().getTime()));
		mDateTv.setText(dateFormat_EN.format(Calendar.getInstance().getTime()));
		// 设置分割线
		mListView.setDivider(getResources().getDrawable(R.color.line));
		// 设置分割线高度
		mListView.setDividerHeight(1);
		mListView.setAdapter(mAdapter);
		// 获取原因列表
		selectDict();
		// getInput("147600217");
		// getInput("147600217")
		// getInput("119504483");
		// getInput("119504483");
		
		mClothTktNoEt.setFocusable(true);  
		mClothTktNoEt.setFocusableInTouchMode(true);  
		
		mClothTktNoEt.requestFocus();
		mClothTktNoEt.requestFocusFromTouch();
		mClothTktNoEt.findFocus();

	}

	/**
	 * 获取时间
	 */
	private void getSystime() {
		showWait();
		RequestServiceImpl.getDateTime(mMIPHandler, IServiceImpl.GET_TIME);
	}

	/**
	 * 初始化事件
	 */
	private void initEvent() {

		mDateLl.setOnClickListener(this);
		mClearImg.setOnClickListener(this);
		mDeleteBtn.setOnClickListener(this);
		mSearchBtn.setOnClickListener(this);
		mSaveBtn.setOnClickListener(this);

		// 使得edittext点击后弹出的软键盘带有搜索按钮
//		mClothTktNoEt.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
//		mClothTktNoEt.setOnEditorActionListener(new OnEditorActionListener() {
//
//			@Override
//			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//				// 点击搜索键
//				if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
//					// toast(actionId + "");
//					startGetInput();
//					return true;
//				}
//
//				return false;
//			}
//		});
		
		
		
		mClothTktNoEt.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER &&   event.getAction() == KeyEvent.ACTION_UP ) {
					//toast(actionId + "");
					startGetInput();
					return true;
				}
				return false;
			}
		});

		/** 暂时取消根据长度来查询的功能 **/
		/*
		 * mClothTktNoEt.addTextChangedListener(new TextWatcher() {
		 * 
		 * @Override public void onTextChanged(CharSequence s, int start, int
		 * before, int count) { }
		 * 
		 * @Override public void beforeTextChanged(CharSequence s, int start,
		 * int count, int after) {
		 * 
		 * }
		 * 
		 * @Override public void afterTextChanged(Editable s) { if (s.length()
		 * >= 9) { startGetInput(); } } });
		 */

		mClothTktNoEt.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// 清空listview的焦点位置，不然弹出键盘焦点不在这
				mAdapter.setFocusIndex(-1);
				return false;
			}
		});

		// mAdapter.setOnDeleteClickListener(new onDeleteClickListener() {
		//
		// @Override
		// public void onClick(int position) {
		// mDeletePostion=position;
		// startDeleteProduct(mDeletePostion);
		// }
		// });

		mAdapter.setOnCheckClickListener(new onCheckClickListener() {

			@Override
			public void onClick(int position, boolean isChecked) {
				mProductList.get(position).isChecked = isChecked;
				mCount = 0;
				for (int i = 0; i < mProductList.size(); i++) {
					if (mProductList.get(i).isChecked == true) {
						mCount++;
					}
				}
				mCountTv.setText("已选择\n" + mCount + "项");
				mCountTv2.setText("Đã chọn" + mCount + "mục");

				// 设置保存按钮状态
				// setBtnStatu();

			}
		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.input_dateLl:
			setDate();
			break;
		case R.id.input_clearImg:
			mClothTktNoEt.setText("");
			break;
		case R.id.input_searchBtn:
			// startGetInput();
			startGetInputList();
			break;
		case R.id.input_saveBtn:
			startSaveInputList();
			break;
		case R.id.input_deleteBtn:

			startDeleteInputList();

			break;

		default:
			break;
		}
	}

	/**
	 * 准备查询已录入的数据，根据日期和车号
	 */
	private void startGetInputList() {
		String machineNo = mMachineNoEt.getText().toString().trim();

		getInputList(machineNo);
	}

	/**
	 * 准备查询数据 根据三联单号
	 */
	private void startGetInput() {
		String clothTktNo = mClothTktNoEt.getText().toString().trim();
		String jobNum = (String) SharedPreUtil.getValue(this, SharedPreUtil.YHM, "");
		if (TextUtils.isEmpty(clothTktNo)) {
			SimpleDialog.show(this, "三联单号不能为空!\nMã số ba liên không được để trống");
			return;
		}
		for (ProductInputEntity product : mProductList) {
			if (clothTktNo.equals(product.MACHINENO + product.CLOTHTKTNO)) {
				SimpleDialog.show(this, "该三联单号已存在,请不要重复录入!\nMã số ba liên này đã tồn tại, vui lòng không nhập lại");
				mClothTktNoEt.setText("");
				return;
			}
		}
		getInput(clothTktNo, jobNum);
	}

	/**
	 * 保存录入的产量
	 */
	private void startSaveInputList() {

		// 每次保存之前都要进行清空，可能存在上一次保存失败的情况下，数据还存在list中
		mSaveProductList.clear();
		for (int i = 0; i < mProductList.size(); i++) {
			if (mProductList.get(i).isChecked) {
				// 添加到需要保存的列表中
				mSaveProductList.add(mProductList.get(i));

			}
		}
		if (mProductList.size() == 0) {
			SimpleDialog.show(this, "当前列表为空，请添加数据！\nBảng trước trống, vui lòng nhập dữ liệu");
			stopWait();
			return;
		}

		if (mSaveProductList.size() == 0) {
			SimpleDialog.show(this, "请勾选需要保存的数据！\nVui lòng chọn dữ liệu cần lưu");
			stopWait();
			return;
		}
		for (ProductInputEntity product : mSaveProductList) {
			if (TextUtils.isEmpty(product.MACHINE_SPEED)) {
				SimpleDialog.show(this, "车速不能为空！\nTốc độ máy không được để trống");
				stopWait();
				return;
			}
			if (TextUtils.isEmpty(product.ROTATION_RATE)) {
				SimpleDialog.show(this, "转速不能为空！\nSố vòng không được để trống");
				stopWait();
				return;
			}

			if (TextUtils.isEmpty(product.ONDUTY_FRAMES) && TextUtils.isEmpty(product.CHANGE_FRAMES) && TextUtils.isEmpty(product.TAKEDUTY_FRAMES)) {
				SimpleDialog.show(this, "格数不能为空！\nSố khấc không được để trống");
				stopWait();
				return;
			}
			if ("0".equals(product.REQUIREWEIGHT)||"0.0".equals(product.REQUIREWEIGHT)) {
				SimpleDialog.show(this, "要求重量不能为0，请重新录入正确的格数！\nTrọng lượng yêu cầu không được là 0, vui lòng nhập số khấc chính xác");
				stopWait();
				return;
			}
			
			if (TextUtils.isEmpty(product.CLASSES)) {
				SimpleDialog.show(this, "请选择班次！\nVui lòng chọn ca làm");
				stopWait();
				return;
			}

			if(!TextUtils.isEmpty(product.REASONS)&&product.REASONS.contains("(")){
				product.REASONS=product.REASONS.substring(0,product.REASONS.indexOf("("));
			}
			if(!TextUtils.isEmpty(product.CLASSES)&&product.CLASSES.contains("(")){
				product.CLASSES=product.CLASSES.substring(0,product.CLASSES.indexOf("("));
			}


		}
		saveInputList();
	}

	/**
	 * 准备进行删除操作
	 */
	private void startDeleteInputList() {
		List<String> PKIDList = new ArrayList<String>();

		for (int i = 0; i < mProductList.size(); i++) {
			if (mProductList.get(i).isChecked) {
				mDeleteProductList.add(mProductList.get(i));

				// 添加到需要保存的列表中
				if (!TextUtils.isEmpty(mProductList.get(i).PKID)) {
					PKIDList.add(mProductList.get(i).PKID);
				}

			}
		}
		if (mDeleteProductList.size() == 0) {
			SimpleDialog.show(this, "请勾选需要删除的数据！\nVui lòng chọn dữ liệu cần xóa");
			stopWait();
			return;
		}
		if (mProductList.size() == 0) {
			SimpleDialog.show(this, "当前列表为空，请添加数据！\nBảng trước trống, vui lòng nhập dữ liệu");
			stopWait();
			return;
		}

		deleteInputProduct(PKIDList);
	}

	/**
	 * 获取下拉框列表的值
	 */
	private void selectDict() {
		showWait();
		RequestServiceImpl.selectDict(mMIPHandler, IServiceImpl.SELECTDICT, TableNo.REASONS);
	}

	/**
	 * 根据三联单号查询数据
	 * 
	 * @param clothTktNo
	 */
	private void getInput(String clothTktNo, String jobNum) {

		showWait();
		if(isAllow){
			RequestServiceImpl.getInput(mMIPHandler, IServiceImpl.GETINPUT_R, clothTktNo, jobNum,mJobDate);
			isAllow=false;
		}
		
	}

	/**
	 * 保存
	 */
	private void saveInputList() {
		showWait();
		String userBean = (String) SharedPreUtil.getValue(this, SharedPreUtil.USERBEAN, "");
		RequestServiceImpl.saveInputlist(mMIPHandler, IServiceImpl.SAVEINPUTLIST_R, userBean, mSaveProductList,mBmmc);
	}

	/**
	 * 查询该工号当前日期已经保存的数据
	 */
	private void getInputList(String machineNo) {

		showWait();
		String userBean = (String) SharedPreUtil.getValue(this, SharedPreUtil.USERBEAN, "");
		RequestServiceImpl.getInputList(mMIPHandler, IServiceImpl.GET_INPUT_LIST,userBean, mJobNum, mJobDate, mBmmc, machineNo);
	}

	/**
	 * 删除(工资产量录入)
	 * 
	 * @param
	 */
	private void deleteInputProduct(List<String> PKIDList) {
		showWait();
		String userBean = (String) SharedPreUtil.getValue(this, SharedPreUtil.USERBEAN, "");
		RequestServiceImpl.deleteInputProduct(mMIPHandler, IServiceImpl.DELETE_INPUT_PRODUCT, userBean, PKIDList);
	}

	/**
	 * 检查listview是否为空
	 */
	private void checkListview() {
		if (mProductList.size() > 0) {
			mListView.setVisibility(View.VISIBLE);
		} else {
			mListView.setVisibility(View.GONE);
		}
	}

	// @Override
	// public boolean onKeyDown(int keyCode, KeyEvent event) {
	// if (keyCode == KeyEvent.KEYCODE_BACK) {
	// return super.onKeyDown(keyCode, event);
	// }
	// if (isHandleKey && keyCode <= 6) {
	// return super.dispatchKeyEvent(event);
	// }
	// if (isHandleKey && mScanGun.isMaybeScanning(keyCode, event)) {
	// return true;
	// }
	// return super.onKeyDown(keyCode, event);
	// }
	//
	// @Override
	// public boolean dispatchKeyEvent(KeyEvent event) {
	// if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
	// return super.dispatchKeyEvent(event);
	// }
	// // 拦截物理键盘事件
	// if (isHandleKey && event.getKeyCode() > 6) {
	// if (event.getAction() == KeyEvent.ACTION_DOWN) {
	// this.onKeyDown(event.getKeyCode(), event);
	// return true;
	//
	// } else if (event.getAction() == KeyEvent.ACTION_UP) {
	// this.onKeyUp(event.getKeyCode(), event);
	// return true;
	// }
	// return true;
	// }
	// return super.dispatchKeyEvent(event);
	// }

/*	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		Log.e("dispatchKeyEvent", event.getKeyCode() + "");
		// toast("dispatchKeyEvent" + event.getKeyCode() + "");
		// 拦截物理键盘事件
		// if (event.getKeyCode() >= KeyEvent.KEYCODE_0 && event.getKeyCode() !=
		// KeyEvent.KEYCODE_DEL) {
		// if (event.getAction() == KeyEvent.ACTION_DOWN) {
		// mScanGun.isMaybeScanning(event.getKeyCode(), event);
		// return true;
		// }
		// return true;
		// }
		// 拦截回车键，成功解决焦点跳行的问题
		if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {

			return true;
		}
		return super.dispatchKeyEvent(event);
	}*/

	private Calendar getDefaultDate(){
		Calendar calendar = Calendar.getInstance();
		// 获取当前年月日
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		int hour=calendar.get(Calendar.HOUR_OF_DAY);
		int minute=calendar.get(Calendar.MINUTE);
		if(hour<7||(hour==7&&minute<30)){
			day-=1;
		}
		calendar.set(year, month, day);
		return calendar;
		}
	
	/**
	 * 设置日期
	 */
	private void setDate() {
		// 初始化日历信息
		Calendar calendar = Calendar.getInstance();
		// 获取当前年月日
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		int hour=calendar.get(Calendar.HOUR_OF_DAY);
		int minute=calendar.get(Calendar.MINUTE);
		if(hour<7||(hour==7&&minute<30)){
			day-=1;
		}
		Log.d("setDate", year + "-" + month + "-" + day);
		/**
		 * context：当前上下文； callback：OnDateSetListener日期改变监听器； year：初始化的年；
		 * monthOfYear：初始化的月（从0开始计数，所以实际应用时需要加1）； dayOfMonth：初始化的日；
		 */
		try{
			String[] time= mJobDate.split("-");
			DatePickerDialog datePickerDialog = new DatePickerDialog(this, mOnDateSetListenernew,Integer.parseInt(time[0]), Integer.parseInt(time[1])-1, Integer.parseInt(time[2]));
			datePickerDialog.show();
		}catch (Exception e){

		}

	}

	/**
	 * 日期选择监听器
	 */
	OnDateSetListener mOnDateSetListenernew = new OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
			String date = year + "-" + String.format("%02d", month + 1) + "-" + String.format("%02d", dayOfMonth);
		
			mDateTv.setText(date);
			mJobDate = year + "-" + String.format("%02d", month + 1) + "-" + String.format("%02d", dayOfMonth);
			for (ProductInputEntity product : mProductList) {
				product.JOBDATE = mJobDate;
				mAdapter.notifyDataSetChanged();
			}

		}
	};

	@Override
	public void onPostHandle(int requestType, Object objBody, boolean error) {
		stopWait();
		String msg = "";
		String opt = "";
		if (error) {
			switch (requestType) {
			case IServiceImpl.GET_INPUT_LIST:

				try {
					JSONObject jsonObj = new JSONObject((String) objBody);
					msg = jsonObj.optString("MSG_INFO");
					opt = jsonObj.optString("OPT_FLAG");
					if ("0".equals(opt)) {
						JSONArray resultArray = jsonObj.optJSONArray("result");
						Gson gson = new Gson();
						List<ProductInputEntity> productList = gson.fromJson(resultArray.toString(), new TypeToken<List<ProductInputEntity>>() {
						}.getType());
						mProductList.clear();
						mProductList.addAll(productList);
						mAdapter.notifyDataSetChanged();
						checkListview();
					} else if ("1".equals(opt)) {
						SimpleDialog.show(this, msg);

					} else if ("2".equals(opt)) {
						SimpleDialog.show(this, msg);

					} else if ("3".equals(opt)) {
						SimpleDialog.show(this, msg);
					}

				} catch (Exception e) {
					e.printStackTrace();

				}

				break;
			case IServiceImpl.GETINPUT_R:

				try {
					
					isAllow=true;
					JSONObject jsonObj = new JSONObject((String) objBody);
					msg = jsonObj.optString("MSG_INFO");
					opt = jsonObj.optString("OPT_FLAG");
					if ("0".equals(opt)) {
						ProductInputEntity product = new ProductInputEntity();
						product = ParseUtils.parse(objBody.toString(), ProductInputEntity.class);
						// 设置员工工号
						product.JOB_NUM = mJobNum;
						// 设置日期
						product.JOBDATE = mJobDate;
						// 设置默认勾选
						product.isChecked = true;
						
						/********************************2017年12月2日 修改 ****************************/
						/************新增时如果列表有相同车号的记录，则复制该车号的“车速、转速、班次”到新的记录中***********/
						
						for (ProductInputEntity savedProduct : mProductList) {
							if(product.MACHINENO.equals(savedProduct.MACHINENO)){
								product.MACHINE_SPEED=savedProduct.MACHINE_SPEED;
								product.ROTATION_RATE=savedProduct.ROTATION_RATE;
								product.CLASSES=savedProduct.CLASSES;
								break;
							}
						}										
						/***********************************结束************************************/
						// 每次在第一行增加数据
						mProductList.add(0, product);
						mAdapter.notifyDataSetChanged();
						checkListview();
						// 查询成功后，清空输入框
						mClothTktNoEt.setText("");
					} else if ("1".equals(opt)) {
						SimpleDialog.show(this, msg);
					} else if ("2".equals(opt)) {
						SimpleDialog.show(this, msg);
					} else if ("3".equals(opt)) {
						SimpleDialog.show(this, msg);
					} else if ("4".equals(opt)) {
						SimpleDialog.show(this, msg);
					}

				} catch (Exception e) {
					e.printStackTrace();

				}
				// toast(msg);
				break;
			case IServiceImpl.SAVEINPUTLIST_R:

				try {
					JSONObject jsonObj = new JSONObject((String) objBody);
					msg = jsonObj.optString("MSG_INFO");
					opt = jsonObj.optString("OPT_FLAG");
					if ("0".equals(opt)) {

						SimpleDialog.show(this, "您已成功保存" + mSaveProductList.size() + "条数据！"+"\nĐã lưu thành công "+mSaveProductList.size()+" số liệu");
						// 保存成功后不进行业务逻辑了，2017年8月7日 功能修改
					
				
						// 保存成功后需要将以保存的数据改为不勾选，2017年8月16日 功能修改
//						for (int i = 0; i < mProductList.size(); i++) {
//
//							mProductList.get(i).isChecked = false;
//							mAdapter.notifyDataSetChanged();
//						}
						//保存成功后需要重新调用查询接口，刷新列表 2017年8月24日 功能修改
						
						
						startGetInputList();
						
						//
						// for (int i = 0; i < mProductList.size(); i++) {
						// if (mProductList.get(i).isChecked) {
						// mProductList.remove(i);
						// }
						// }
						// mSaveProductList.clear();
						//
						// mAdapter.notifyDataSetChanged();
						// mClothTktNoEt.setText("扫描布票条形码（自动添加到列表）");

					} else if ("1".equals(opt)) {
						SimpleDialog.show(this, msg);

					} else if ("2".equals(opt)) {
						SimpleDialog.show(this, msg);

					}
					 else if ("3".equals(opt)) {
							SimpleDialog.show(this, msg);
					}

				} catch (Exception e) {
					e.printStackTrace();

				}
				// toast(msg);
				break;
			case IServiceImpl.DELETE_INPUT_PRODUCT:

				try {
					JSONObject jsonObj = new JSONObject((String) objBody);
					msg = jsonObj.optString("MSG_INFO");
					opt = jsonObj.optString("OPT_FLAG");
					if ("0".equals(opt)) {
			
						SimpleDialog.show(this, "您已成功删除" + mCount + "条数据！"+"\nĐã xóa thành công "+mCount+"số liệu");
						// for (int i = 0; i < mProductList.size(); i++) {
						// if (mProductList.get(i).isChecked) {
						// mProductList.remove(i);
						// }
						// }
						//
						for (int i = 0; i < mDeleteProductList.size(); i++) {
							for (int j = 0; j < mProductList.size(); j++) {
								if ((mProductList.get(j).MACHINENO + mProductList.get(j).CLOTHTKTNO).equals(mDeleteProductList.get(i).MACHINENO
										+ mDeleteProductList.get(i).CLOTHTKTNO)) {
									mProductList.remove(j);
								}
							}
						}
						mDeleteProductList.clear();

						mAdapter.notifyDataSetChanged();
						checkListview();
						mCount = 0;
						mCountTv.setText("已选择\n" + mCount + "项");
						mCountTv2.setText("Đã chọn" + mCount + "mục");
						// setBtnStatu();

					} else if ("1".equals(opt)) {
						SimpleDialog.show(this, msg);

					} else if ("2".equals(opt)) {
						SimpleDialog.show(this, msg);
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case IServiceImpl.SELECTDICT:

				try {
					Gson gson = new Gson();
					List<SpinnerEntity> spinnerEntityList = gson.fromJson(objBody.toString(), new TypeToken<List<SpinnerEntity>>() {
					}.getType());
					for (SpinnerEntity spinnerEntity : spinnerEntityList) {
						mSpList.add(spinnerEntity.fieldText);
					}
					// 将获取到的splist（下拉框）传给适配器
					mAdapter.setSpList(mSpList);

				} catch (Exception e) {
					e.printStackTrace();

				}
				break;
				case IServiceImpl.GET_TIME:
					try {
						if(objBody.toString().length()>10){
							mJobDate=objBody.toString().substring(0,10);
							mDateTv.setText(mJobDate);
						}
					} catch (Exception e) {
						e.printStackTrace();

					}
					break;
			}
		} else {
//			switch (requestType) {
//			case IServiceImpl.GETINPUT_R:
//				toast("服务器未响应，查询失败！");
//				break;
//			case IServiceImpl.SAVEINPUTLIST_R:
//				toast("保存失败！");
//				break;
//			case IServiceImpl.SELECTDICT:
//				toast("链接失败！");
//				break;
//			}
			SimpleDialog.show(this, objBody.toString());
		}
	}

	/**
	 * 保存数据
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		outState.putSerializable(PRODUCTLIST, (Serializable) mProductList);
		outState.putString(CLOTHTKTNO, mClothThtNo);
	}

	@Override
	protected void onDestroy() {
		// toast("onDestroy");
		super.onDestroy();
	}

}
